<?php
// public/reports/personnel.php
declare(strict_types=1);

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/flash.php';

require_login();
$user = current_user();

// Only admin/hr can view reports
if (!in_array($user['role'], ['admin','hr'], true)) {
    set_flash('danger', 'You are not authorized to access reports.');
    header('Location: /ldp/public/dashboard.php');
    exit;
}

global $pdo;

$q    = trim($_GET['search'] ?? '');
$year = trim($_GET['year'] ?? '');

$params = [];
$where  = [];

// Keyword search
if ($q !== '') {
    $where[] = "(employee_id LIKE :q1
              OR name LIKE :q2
              OR position LIKE :q3
              OR employee_type LIKE :q4
              OR status LIKE :q5
              OR address LIKE :q6
              OR cpnumber LIKE :q7
              OR type LIKE :q8
              OR level LIKE :q9)";
    $params = array_merge($params, [
        ':q1' => "%$q%",
        ':q2' => "%$q%",
        ':q3' => "%$q%",
        ':q4' => "%$q%",
        ':q5' => "%$q%",
        ':q6' => "%$q%",
        ':q7' => "%$q%",
        ':q8' => "%$q%",
        ':q9' => "%$q%",
    ]);
}

// Fetch training data
$sql = "SELECT * FROM training";
if ($where) {
    $sql .= " WHERE " . implode(" AND ", $where);
}
$sql .= " ORDER BY updated_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

render_header('Training Report', 'reports');
$flash = get_flash();
?>

<!-- Print CSS -->
<style>
@media print {
    /* Hide everything above table */
    .btn-print,
    .met,
    .btn-danger,
    #part1,
    #part2,
    .card2,
    .alert,
    .ml-2,
    .input-group,
    .input-group-append {
        display: none !important;
    }

    /* Table styling for print */
    table {
        width: 100%;
        border-collapse: collapse;
    }
    table, th, td {
        border: 1px solid #000;
    }
}
</style>

<!-- Flash Message -->
<?php if ($flash): ?>
<div class="alert alert-<?= htmlspecialchars($flash['type']) ?>">
    <?= htmlspecialchars($flash['message']) ?>
</div>
<?php endif; ?>

<!-- Search Form -->
<form method="GET" class="met" id="part1">
    <div class="input-group mr-2">
        <input type="text" class="searchInput" style="width:400px;font-size:18px;" placeholder="Search..." onkeyup="filterTable(this)">
       
    </div>
    <div class="input-group-append">
        <button type="submit" class="btn btn-outline-secondary"><i class="fas fa-search"></i> Search</button>
        <a href="personnel.php" class="btn btn-outline-dark">Reset</a>
    </div>
</form>

<form method="GET" class="met" id="part1">
    <div class="input-group mr-2">
        <input type="text" class="searchInput2" style="width:400px;font-size:18px;" placeholder="Year or Date" onkeyup="filterTableDate(this)">
    </div>
    <div class="input-group-append">
        <button type="submit" class="btn btn-outline-secondary"><i class="fas fa-search"></i> Search</button>
        <a href="personnel.php" class="btn btn-outline-dark">Reset</a>
    </div>
</form>


<!-- Export PDF Button -->
<div class="ml-2" id="part2">
    <?php $query = http_build_query(['search' => $q]); ?>
    <a href="export_personnel.php?format=pdf&<?= $query ?>" class="btn btn-sm btn-danger"><i class="fas fa-file-pdf"></i> Export PDF</a>
</div>

<!-- Print Button -->
<a class="btn btn-success btn-print" href="#" onclick="window.print()"><i class="glyphicon glyphicon-print"></i> Print</a>

<!-- START Table Section -->
<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <br>
            <!-- Report Header -->
            <table class="header" style="width:100%; margin-bottom:10px;">
                <tr>
                    <td><img src="http://localhost/ldp/public/assets/img/logo.png" alt="Logo" style="width:90px;height:90px;border-radius:50%;"></td>
                    <td style="width:70%;">
                        Republic of the Philippines<br>
                        <strong>DR. EMILIO B. ESPINOSA SR., MEMORIAL STATE COLLEGE OF AGRICULTURE AND TECHNOLOGY</strong><br>
                        Cabitan, Mandaon, Masbate | <a href="http://www.debesmscat.edu.ph">www.debesmscat.edu.ph</a><br>
                        <strong style="font-size:23px;">TRAINING REPORTS</strong>
                    </td>
                    <td style="width:15%;">
                        <img src="http://localhost/ldp/public/assets/img/l.png" alt="Logo" style="width:90px;height:90px;">
                    </td>
                </tr>
            </table>

            <!-- Training Table -->
            <table class="table table-striped mb-0" id="myTable">
                <thead>
                    <tr>
                        <th>Training Title of L&D</th>
                        <th>Training Description</th>
                        <th>Category</th>
                        <th>Type of L&D</th>
                        <th>Training Schedule From</th>
                        <th>Training Schedule Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$rows): ?>
                        <tr>
                            <td colspan="6" class="text-center text-muted p-4">No Training records found.</td>
                        </tr>
                    <?php else: foreach ($rows as $p): ?>
                        <tr>
                            <td><?= htmlspecialchars($p['title'] ?? '') ?></td>
                            <td><?= htmlspecialchars($p['description'] ?? '') ?></td>
                            <td>
                                <?php if (!empty($p['leveloftraining'])): ?>
                                    <span class="badge badge-info"><?= htmlspecialchars($p['leveloftraining']) ?></span>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($p['lnd'] ?? '') ?></td>
                            <td><?= htmlspecialchars($p['date_from'] ?? '') ?></td>
                            <td><?= htmlspecialchars($p['created_at'] ?? '') ?></td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- JavaScript Table Filter -->
<script>
function filterTable(input) {
    const filter = input.value.toUpperCase();
    const table = document.getElementById('myTable');
    const rows = table.getElementsByTagName('tr');

    for (let i = 1; i < rows.length; i++) { // skip header
        const cells = rows[i].getElementsByTagName('td');
        let match = false;

        for (let j = 0; j < cells.length; j++) {
            const text = cells[j].textContent || cells[j].innerText;
            if (text.toUpperCase().indexOf(filter) > -1) {
                match = true;
                break;
            }
        }
        rows[i].style.display = match ? '' : 'none';
    }
}


function filterTableDate(input) {
    const filter = input.value.toUpperCase();
    const table = document.getElementById('myTable');
    const rows = table.getElementsByTagName('tr');

    for (let i = 1; i < rows.length; i++) { // skip header row
        const cells = rows[i].getElementsByTagName('td');
        let match = false;

        // Only check columns 5 (index 4) and 6 (index 5)
        for (let j = 4; j <= 5; j++) {
            if (cells[j]) {
                const text = cells[j].textContent || cells[j].innerText;
                if (text.toUpperCase().indexOf(filter) > -1) {
                    match = true;
                    break;
                }
            }
        }

        rows[i].style.display = match ? '' : 'none';
    }
}
</script>

<?php render_footer(); ?>
